<template>
  <Dialog
    v-model="show"
    @confirm="handleSubmit"
    :title="viewOnly ? t('goods_list.驳回原因') : t('goods_list.驳回上架')"
    width="500"
    :showFooter="!viewOnly"
  >
    <el-form :model="form" label-width="100px" ref="formRef" :rules="rules">
      <el-form-item :label="t('goods_list.驳回原因')" prop="rejectReason">
        <el-input
          type="textarea"
          v-model="form.rejectReason"
          :rows="4"
          :disabled="viewOnly"
          :placeholder="t('goods_list.请输入驳回原因')"
        />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, computed } from "vue";
import { useI18n } from "vue-i18n";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";

const { t } = useI18n();

const show = defineModel();
const emit = defineEmits(["success"]);
const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
});

const form = ref({
  rejectReason: "",
  status: -1, // 驳回状态
});

const viewOnly = computed(() => {
  return props.data?.[0]?.status != 0;
});

const rules = ref({
  rejectReason: [
    { required: true, message: t('goods_list.请输入驳回原因'), trigger: "blur" },
    {
      min: 5,
      max: 200,
      message: t('goods_list.驳回原因长度应在5到200个字符之间'),
      trigger: "blur",
    },
  ],
});

watch(
  () => show.value,
  (newVal) => {
    if (newVal) {
      setTimeout(() => {
        // 如果是查看模式，则填充已有驳回原因
        if (viewOnly.value) {
          form.value.rejectReason = props.data?.[0]?.rejectReason || "";
        } else {
          form.value.rejectReason = "";
        }
      }, 100);
    }
  },
  { deep: true }
);

const formRef = ref();

const handleSubmit = () => {
  if (viewOnly.value) {
    show.value = false;
    return;
  }

  formRef.value.validate(async (valid) => {
    if (valid) {
      await Api.sku_check({
        ids: props.data.map((item) => item.id),
        status: -1,
        rejectReason: form.value.rejectReason,
      }).then((res) => {
        if (res.status === 200) {
          ElMessage.success(t('goods_list.驳回成功'));
          emit("success");
          show.value = false;
        }
      });
    }
  });
};
</script>
